/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.race.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.lczyfz.istep.common.utils.excel.ExportExcel;
import com.lczyfz.istep.common.utils.excel.ImportExcel;
import com.lczyfz.istep.modules.race.entity.RaceUser;
import com.lczyfz.istep.modules.race.service.RaceUserService;
import com.lczyfz.istep.modules.sys.utils.UserUtils;
import org.apache.poi.util.SystemOutLogger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.common.utils.StringUtils;
import com.lczyfz.istep.modules.race.entity.RaceTeam;
import com.lczyfz.istep.modules.race.service.RaceTeamService;

import java.util.List;

/**
 * 竞赛团队列表Controller
 * @author CY
 * @version 2017-04-17
 */
@Controller
@RequestMapping(value = "${adminPath}/race/raceTeam")
public class RaceTeamController extends BaseController {

	@Autowired
	private RaceTeamService raceTeamService;
	@Autowired
	private RaceUserService raceUserService;

	@ModelAttribute
	public RaceTeam get(@RequestParam(required=false) String id) {
		RaceTeam entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = raceTeamService.get(id);
		}
		if (entity == null){
			entity = new RaceTeam();
		}
		return entity;
	}
	
	@RequiresPermissions("race:raceTeam:view")
	@RequestMapping(value = {"list", ""})
	public String list( RaceTeam raceTeam, HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("raceUsers", raceTeamService.findAllListUser());
		Page<RaceTeam> page = raceTeamService.findPage(new Page<RaceTeam>(request, response), raceTeam); 
		model.addAttribute("page", page);
		return "modules/race/raceTeamList";
	}

	@RequiresPermissions("race:raceTeam:view")
	@RequestMapping(value = "form")
	public String form(RaceTeam raceTeam, Model model) {
		if (raceTeam.getId() == null) {
			model.addAttribute("raceTeam", raceTeam);
			return "modules/race/raceTeamForm";
		}else {
			  model.addAttribute("raceUsers", raceTeamService.findAllListUser());
              model.addAttribute("raceTeam", raceTeam);
			  return "modules/race/raceTeamEditor";
		}
	}

	@RequiresPermissions("race:raceTeam:edit")
	@RequestMapping(value = "save")
	public String save(RaceTeam raceTeam, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, raceTeam)){
			return form(raceTeam, model);
		}
		if (raceTeam.getId() != null){
          List<RaceTeam> raceTeams = raceTeamService.selectRaceTeamId(raceTeam.getId());
            for (RaceTeam raceTeam1 : raceTeams){
                RaceUser raceUser = raceUserService.findId(raceTeam1.getUserId());
				raceUser.setTeamId(raceTeam.getTeamName());
				raceUserService.save(raceUser);
			}
		}

		List<RaceTeam> raceTeamlist = raceTeamService.findByName(raceTeam.getTeamName());
		if (raceTeamService.get(raceTeam) == null) {
			if (raceTeamlist.size()!=0) {
				addMessage(redirectAttributes, "该团队已存在，保存团队失败");
				return "redirect:" + Global.getAdminPath() + "/race/raceTeam/?repage";
			}
		} else if (raceTeamlist.size() != 0)  {
				if (null != raceTeamlist && !raceTeam.getId().equals(raceTeamlist.get(0).getId())) {
					addMessage(redirectAttributes, "编辑团队失败，该团队已存在");
					return "redirect:" + Global.getAdminPath() + "/race/raceTeam/?repage";
				}
			}
		        raceTeamService.save(raceTeam);
		return "redirect:" + Global.getAdminPath() + "/race/raceTeam/?repage";

	}
	
	@RequiresPermissions("race:raceTeam:edit")
	@RequestMapping(value = "delete")
	public String delete(RaceTeam raceTeam, RedirectAttributes redirectAttributes) {
		List<RaceUser> raceUsers = raceTeamService.findAllListUser();
		for (RaceUser raceUser1 : raceUsers){
			if (raceUser1 != null && raceUser1.getTeamId()!= null && raceUser1.getTeamId().equals(raceTeam.getTeamName())){
				raceUser1.setTeamId("");
				raceUserService.save(raceUser1);
			}
		}
		raceTeamService.delete(raceTeam);
		addMessage(redirectAttributes, "删除团队成功");
		return "redirect:"+Global.getAdminPath()+"/race/raceTeam/?repage";
	}

	@RequiresPermissions("race:raceTeam:edit")
	@RequestMapping(value = "deleteEditor")
	public String deleteEditor(RaceUser raceUser, String uid, Model model,String tid) {


	    raceUser =	raceUserService.findId(uid);
		raceUser.setTeamId("");
		raceUserService.save(raceUser);
		RaceTeam raceTeam = raceTeamService.findTeamId(tid);
		model.addAttribute("raceTeam", raceTeam);
		model.addAttribute("raceUsers", raceTeamService.findAllListUser());
		raceTeamService.deleteRaceUserId(uid);
		return "modules/race/raceTeamEditor";
	}

	//团队详情
   @ResponseBody
   @RequestMapping(value = "teamDetails")
	public List<RaceUser> teamDetails(String teamId){
	   return  raceTeamService.teamDetails(teamId);
   }

	/**
	 * 下载导入竞赛账号数据模板
	 *
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "竞赛团队模板.xlsx";
			List<RaceTeam> list = Lists.newArrayList();
			RaceTeam raceTeam = new RaceTeam();
			raceTeam.setTeamName("xx团队名");
			list.add(raceTeam);
			logger.debug("=Evan==竞赛团队导入模板==" + list);
			new ExportExcel("竞赛团队", RaceTeam.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/race/raceTeam/?repage";
	}


	/**
	 * 导入学生账号
	 *
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		List<RaceTeam> raceTeams = raceUserService.findAllClassList();
		try {
			int successNum = 0;
			int failureNum = 0;
			int teamNum = 0;
			//StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<RaceTeam> list = ei.getDataList(RaceTeam.class);
			//logger.debug("=Evan==importFile==" + list);
			for (RaceTeam raceTeam : list) {
				for (RaceTeam raceTeam1 : raceTeams) {
					if (raceTeam.getTeamName().equals(raceTeam1.getTeamName())) {
						teamNum++;
					}
				}
				if (teamNum == 0){
					raceTeamService.save(raceTeam);
					successNum++;
				}else {
					failureNum++;
				}
				teamNum = 0;
			}
			addMessage(redirectAttributes, "已成功导入： " + successNum + "条、    失败：" + failureNum + "条");
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
		}

		return "redirect:"+Global.getAdminPath()+"/race/raceTeam/?repage";
	}
}